//
//  AppsViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14-10-9.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#define  TAG_OFF_NUMBER 1081
#import "AppsViewController.h"

#import "PublicListController.h"
#import "PublicInforDetailViewController.h"
#import "MessageViewController.h"
#import "PublicAccount.h"
#import "PublicAccountDao.h"
#import "SYTabBar.h"
#import "SYTabBarItem.h"
#import "DataDictDao.h"
@interface AppsViewController ()<SYTabBarDelegate>
{
    NSString * selectNum;
    NSArray *arrayViewcontrollers;
    UIView * buttonBackView;
    NSInteger _tabButtonTag;
    NSInteger lastClikcBtn;
    PublicListController *search;

}

@property (nonatomic, strong) SYTabBar *textSelectionList;
@property (nonatomic, strong) PublicListController *vc1;//我的
@property (nonatomic, strong) PublicListController *vc2;//分类
@property (nonatomic, strong) PublicListController *vc3;//精品
@end

@implementation AppsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //接收公众号关注发生变化的时候广播
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealPublicAttentionNotifier:) name:PUBLIC_ATTENTION_BROADCAST object:nil];
        
        //首页应用变化时广播消息
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealPublicAttentionNotifier:) name:HOMEAPP_CHANGE_BROADCAST object:nil];
        [self updataPublicAppsTimeUp];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    //切换到应用列表时，上次刷新时间超过1个小时后，重新跟新应用列表数据
    NSDate * lastime = [[DE getGlobalVar:LAST_REFRESH_PUBLIC_TIME] dateFromString];
    NSDate * curDate =[NSDate date];
    NSTimeInterval secondsBetweenDates= [curDate timeIntervalSinceDate:lastime];
    if (secondsBetweenDates>60*60) {
        [self updataPublicAppsTimeUp];
    }
}
-(void)viewDidUnload
{
    //页面卸载时，需要清理掉通知消息接收
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:PUBLIC_ATTENTION_BROADCAST object:nil];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    arrayViewcontrollers = [self getViewcontrollers];
    
    [self addTitleBarWithBackBtn:@"应用市场"];
    
    
    self.vc1.title = @"我的";
    self.vc1.kindType=@"2";
    self.vc1.deleget = self;
    
    
    self.vc2.title = @"分类";
    self.vc2.kindType=@"1";
    self.vc2.deleget = self;
    
    self.vc3.kindType=@"0";
    self.vc3.title = @"精品";
    self.vc3.deleget = self;
    
    [self dealPublicAttentionNotifier:nil];
    // [self chooseBtn:0];
    
    //导航栏上面的搜索按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(270.0f, (YNEW)+2, 50.0f, 40.0f);
    [rightBtn addTarget:self action:@selector(showRightBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    rightBtn.imageEdgeInsets = UIEdgeInsetsMake ( 5 ,  10 , 5 , 10 );
    
    [self.titlebar addSubview:rightBtn];
    
    
    _textSelectionList = [[SYTabBar alloc]initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, 35)];

    
    NSMutableArray *tabBarItmes = [[NSMutableArray alloc] initWithCapacity:3];
    //NSString *arrTitles[3] = {@"精品",@"分类",@"我的"};
    NSString *arrTitles[3] = {@"我的",@"分类",@"精品"};
    for (int i = 0; i < 3; i ++)
    {
        SYTabBarItem *itemTempA = [[SYTabBarItem alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 3, 35 ) title:arrTitles[i] selectedImage:nil unselectedImage:nil];
        itemTempA.selectedTitleColor = BASIC_BLUE_COLOR;
        [itemTempA setBackgroundColor:[UIColor whiteColor]];
        [itemTempA setTitleFont:[UIFont systemFontOfSize:15.0f]];
        itemTempA.unselectedTitleColor = [UIColor colorWithRed:0.690 green:0.694 blue:0.698 alpha:1.000];
        itemTempA.tag = i;
        [tabBarItmes addObject:itemTempA];
    }

    //initalize the tab barA
    _textSelectionList = [_textSelectionList initWithSYTabBarItems:tabBarItmes];
    _textSelectionList.tabBarDelegate = self;
    
    //[_textSelectionList selectItemAtIndex:0];
    [_textSelectionList selectItemAtIndex:0];
    [_textSelectionList setShowDividingLine:NO];
    [self.view addSubview:_textSelectionList];
    
    

}

-(void)showRightBtnView:(id)sender
{
    //点击搜索，单独跳转一个搜索页面
    search = [[PublicListController alloc] init];
    search.kindType=@"3";
    search.deleget = self;
    search.title = @"搜索应用";
    search.view.frame = CGRectMake(0,TITLE_BAR_HEGIHT+(YNEW),SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW);
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:search animated:NO];
}

-(void)dealPublicAttentionNotifier:(NSNotification*)notification
{
    //精品
    NSArray * BoutiqueAPP = [PublicAccountDao getPublicAccountWhere:@"where isRecommend = 1" appTyps:nil];
    //设置展示的应用列表
    NSMutableArray * apptypevc1 =[[NSMutableArray alloc]init];
    DataDict * dict = [[DataDict alloc]init];
    dict.dictdataValue =@"应用推荐";
    dict.otheArray =BoutiqueAPP;
    [apptypevc1 addObject:dict];
    
    self.vc3.appType = apptypevc1;
    self.vc3.appAD = [PublicAccountDao getPublicAccountWhere:@"where isBanner = 1" appTyps:nil];; //橱窗应用
    
    [self.vc3.appListTable reloadData];
    
    //分类
    NSArray * apptype = [DataDictDao queryDataDict:APPTYPES];
    self.vc2.appType = [PublicAccountDao getPublicAccountWhere:@"" appTyps:apptype];;
    [self.vc2.appListTable reloadData];
    
    //我的
    NSArray * MyAPP = [PublicAccountDao getSubscribePublicAccount:YES];;
    //设置展示的应用列表
    NSMutableArray * apptypevc3 =[[NSMutableArray alloc]init];
    DataDict * dict3 = [[DataDict alloc]init];
    dict3.dictdataValue =@"我的应用";
    dict3.otheArray =MyAPP;
    [apptypevc3 addObject:dict3];
    self.vc1.appType = apptypevc3;
    [self.vc1.appListTable reloadData];
    
}

-(void)updataPublicAppsTimeUp{
    
    [DE serverCall:@"queryApps" params:@{@"1":@"1"} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        if (success) {
            NSArray *array = [data objectForKey:@"apps"];
            
            [PublicAccountDao updataDBwithSQLiteStatement:array];
            
            [DE setGlobalVar:LAST_REFRESH_PUBLIC_TIME value:[[NSDate date] stringFromDateDB]];
            [self dealPublicAttentionNotifier:nil];
            
            //获取应用分类字典表
            NSArray *appTypesArray = [data objectForKey:@"dict"];
            [DataDictDao updataDataDictWithType:appTypesArray dicttypeId:@"6"];
        }
        
    }];
    
}


/**
 *	@brief	创建APP类型列表选择栏
 *
 *	@return	return value description
 */
-(NSArray *)getViewcontrollers

{
    NSArray* tabBarItems = nil;
    
    _vc1 = [[PublicListController alloc]init];
    _vc2 = [[PublicListController alloc]init];
    _vc3 = [[PublicListController alloc]init];
    
    tabBarItems = @[@{@"viewController":_vc1,@"name":@"我的"},@{@"viewController":_vc2,@"name":@"分类"},@{@"viewController":_vc3,@"name":@"精品"}];
    return tabBarItems;
    
}


- (void)tabBar:(SYTabBar *)tabBar didSelectItem:(SYTabBarItem *)item
{
    [item setBackgroundImage:[UIImage imageNamed:@"button_line2"]];
    UIView* currentView = [self.view viewWithTag:999];
    [currentView removeFromSuperview];
    NSDictionary* data = [arrayViewcontrollers objectAtIndex:item.tag];
    
    UIViewController *viewController = data[@"viewController"];
    
    viewController.view.tag = 999;
    
    viewController.view.frame = CGRectMake(0,35+TITLE_BAR_HEGIHT+(YNEW),SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW);
    [self.view insertSubview:viewController.view aboveSubview:_textSelectionList];
}

@end
